package com.mapapp.flutter_mapapp.persenter;

import android.content.Context;

import com.mapapp.flutter_mapapp.application.Constants;
import com.mapapp.flutter_mapapp.bean.LoginBean;
import com.mapapp.flutter_mapapp.http.ActivityLifeCycleEvent;
import com.mapapp.flutter_mapapp.http.Api;
import com.mapapp.flutter_mapapp.http.HttpUtil;
import com.mapapp.flutter_mapapp.http.ProgressSubscriber;
import com.mapapp.flutter_mapapp.util.SharePreferenceUtil;
import com.mapapp.flutter_mapapp.util.ToastUtils;
import com.mapapp.flutter_mapapp.view.LoginViewInterface;

import rx.subjects.PublishSubject;

public class LoginPersenter {
    private static final String TAG = "LoginPersenter";
    private Context mContext;
    private LoginViewInterface mView;
    private PublishSubject<ActivityLifeCycleEvent> lifecycleSubject;

    public LoginPersenter(LoginViewInterface view, Context context, PublishSubject<ActivityLifeCycleEvent> lifecycleSubject) {
        this.mView = view;
        this.mContext = context;
        this.lifecycleSubject = lifecycleSubject;
    }

    public void login(final String username, final String passwork) {
        HttpUtil.getInstance().toSubscribe(Api.getApiService().login(username, passwork),
                new ProgressSubscriber<LoginBean>(mContext,false) {
                    @Override
                    protected void _onNext(LoginBean data) {
                        String token = data.getToken();
                        SharePreferenceUtil.put(mContext, Constants.APPTOKEN, token);
                        SharePreferenceUtil.put(mContext, Constants.USERNAME, username);
                        SharePreferenceUtil.put(mContext, Constants.PASSWORD, passwork);

                        LoginBean.FtpInfoBean ftpInfo = data.getFtpInfo();
                        if (ftpInfo != null) {
                            SharePreferenceUtil.put(mContext, Constants.FTP_SERVER, ftpInfo.getFtpserver());
                            SharePreferenceUtil.put(mContext, Constants.FTP_USERNAME, ftpInfo.getFtpuser());
                            SharePreferenceUtil.put(mContext, Constants.FTP_PASSWORD, ftpInfo.getFtppwd());
                            SharePreferenceUtil.put(mContext, Constants.FTP_PORT, ftpInfo.getFtpport());
                        }

                        mView.loginSuccess();
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtils.showMessage(mContext, message);
                    }
                }, lifecycleSubject);
    }
}
